package com.suieqian.filter.logFile;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Type;
import java.util.Random;

/**
 * @author lirch
 */
//@ControllerAdvice
//@Order(1)
@Slf4j
public class LogRequestBodyHandler extends RequestBodyAdviceAdapter {

    @Autowired
    HttpServletRequest request;

    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        long startTime = System.currentTimeMillis();
        request.setAttribute("myInterceptor_startTime", startTime);
        String requestId = startTime + getRandom();
        request.setAttribute("myInterceptor_requestId", requestId);
        log.info("请求开始requestId:" + requestId + "===地址:" + request.getRequestURL().toString());
        log.info("请求开始requestId:" + requestId + "===x-manage-session:" + request.getHeader("x-manage-session"));
        log.info("请求开始requestId:" + requestId + "===" + request.getMethod() + "参数:" + JSONUtil.toJsonStr(body));
        return super.afterBodyRead(body, inputMessage, parameter, targetType, converterType);
    }

    /**
     * 获取随机数
     */
    private String getRandom() {
        Random ran = new Random();
        int random = ran.nextInt(10000);
        return String.valueOf(random);
    }

}
